﻿using System;
using System.Xml;
using LuaVM.Core;

namespace LuaVM.Controls
{
	public class LuaSyntaxManager
	{
		XmlDocument m_xml = new XmlDocument();
		XmlNode m_variables = null;
		XmlNode m_functions = null;
		
		public LuaSyntaxManager(string resource)
		{
			m_xml.LoadXml(resource);
			XmlAttribute attr;
			XmlNodeList nodeList = m_xml.SelectNodes("/SyntaxDefinition/RuleSets/RuleSet/KeyWords");
			foreach (XmlNode node in nodeList)
			{
				attr = node.Attributes["name"];
				if (attr == null)
				{
					continue;
				}

				switch (attr.Value)
				{
					case "Plugin variables":
						m_variables = node;
						break;

					case "Plugin functions":
						m_functions = node;
						break;

					default:
						break;
				}
			}

			if (m_variables == null)
			{
				throw new Exception("Syntax definition xml node midding: Plugin variables");
			}

			if (m_functions == null)
			{
				throw new Exception("Syntax definition xml node midding: Plugin functions");
			}
			
			m_xml.Save(Constants.SyntaxFile);
		}

		public void UpdatePlugins(LuaDllPlugin[] plugins)
		{
			while (m_variables.ChildNodes.Count > 0)
			{
				m_variables.RemoveChild(m_variables.FirstChild);
			}

			while (m_functions.ChildNodes.Count > 0)
			{
				m_functions.RemoveChild(m_functions.FirstChild);
			}			

			foreach (LuaDllPlugin plugin in plugins)
			{
				// 插件名称必然要高亮
				CreateKeywordNode(m_variables, plugin.Name);

				if (plugin.ExportedVariables != null)
				{
					foreach (string name in plugin.ExportedVariables)
					{
						CreateKeywordNode(m_variables, name);
					}
				}

				if (plugin.ExportedFunctions != null)
				{
					foreach (string name in plugin.ExportedFunctions)
					{
						CreateKeywordNode(m_functions, name);
					}
				}
			}

			m_xml.Save(Constants.SyntaxFile);
		}		

		void CreateKeywordNode(XmlNode parent, string value)
		{
			XmlNode node = m_xml.CreateElement("Key");
			XmlAttribute attr = m_xml.CreateAttribute("word");
			attr.Value = value;
			node.Attributes.Append(attr);
			parent.AppendChild(node);
		}
	}
}
